<?php
    // BackupTweets version 1.0
    // Simple script to backup all of your tweets and write them to a JSON file
    // Check out the website: <http://www.haykranen.nl/projects/backuptweets>
    // By Hay Kranen <hay at bykr dot org>
    // Released under the GPL v3: http://www.gnu.org/copyleft/gpl.html
    
    // Simple check to see if PHP 5.2 and the JSON lib are installed
   	if (
   	    (version_compare(phpversion(), '5.2.0', '<') == true) ||
   	    (!function_exists('json_encode'))
    ) {
        die ('PHP5.2 or higher and the JSON library is required for this application!');
    } 

    require 'inc/class-http-request.php';
    require 'inc/class-twitter-api.php';

    function out($msg) {
        echo $msg . "<br />";
        flush();
    }

    function backuptweets() {
        global $user, $pass;

        out("\nStarting tweet backup for $user...");
        $tw = new Twitter($user, $pass);

        // First get the number of tweets for this user
        $data = $tw->usersShow();
        if ($tw->getError()) {
            out("Error getting data! Sorry, try again later :(");
            return;
        }

        $statuses = $data['statuses_count'];
        $pages = ceil($statuses / 200);
        out($statuses . " statuses...");
        out($pages . " pages...");
        out("Getting 'm all!");

        // Now go get 'm..
        $tweets = array();
        for ($page = 1; $page <= $pages; $page++) {
            out("Fetching page $page/$pages");
            $data = $tw->statusesUserTimeline($page);
            if ($tw->getError()) {
                out("Error getting data! Sorry, try again later :(");
                return;
            }

            $tweets = array_merge($tweets, $data);
            out("Done!");
        }

        out("Saving as JSON");
        file_put_contents("tweets/$user.json", json_encode($tweets));

        out("Done!");
    }

    if (!empty($_POST)) {
        $user = htmlspecialchars($_POST['user']);
        $pass = htmlspecialchars($_POST['pass']);
    }
?>